package com.eg366.nioLearn.baseSocket.chapter02.UDP;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPEchoClientTimeOut2 {

	/* 超时时间3000毫秒 */
	public static final int TIMEOUT = 30000;
	/* 最大尝试次数 */
	public static final int MAXTRIES = 5;

	public static void main(String[] args) throws IOException {
		args = new String[]{"127.0.0.1", "eg366ddddddddd222", "5555"};
		if (args.length < 2 || args.length > 3) {
			throw new IllegalArgumentException(
					"Parameter(s): <Server> <Word> [<Port>]");
		}

		/* UDP服务器端IP地址 */
		InetAddress serverAddress = InetAddress.getByName(args[0]);
		/* 待发送的数据 */
		byte[] bytesSend = args[1].getBytes();
		/* UDP服务器端端口号 */
		int servPort = args.length == 3 ? Integer.parseInt(args[2]) : 7;

		/* 创建UDP套接字 */
		DatagramSocket socket = new DatagramSocket();
		/* 设置套接字超时时间 */
		socket.setSoTimeout(TIMEOUT);

		/* 创建发送的数据报文 */
		DatagramPacket sendPacket = new DatagramPacket(bytesSend,
				bytesSend.length, serverAddress, servPort);

		/* 创建接收的数据报文 */
		DatagramPacket receivePacket = new DatagramPacket(
				new byte[bytesSend.length], bytesSend.length);

		int tries = 0;
		boolean receiveResponse = false;

		do {
			System.out.println("Send Data:" + new String(bytesSend));
			/* 发送数据报文 */
			socket.send(sendPacket);
			try {
				/* 接收数据报文 */
				socket.receive(receivePacket);
				if (!receivePacket.getAddress().equals(serverAddress)) {
					throw new IOException(
							"Received packet from an unknow source");
				}
				receiveResponse = true;
			} catch (InterruptedIOException e) {
				tries += 1;
				System.out.println("Time out, " + (MAXTRIES - tries)
						+ " more tries...");
			}
		} while (!receiveResponse && tries < MAXTRIES);

		if (receiveResponse) {
			System.out.println("Received: "
					+ new String(receivePacket.getData()));
		} else {
			System.out.println("No response -- giving up");
		}
		/* 关闭套接字 */
		socket.close();
	}
}
